<script lang="ts" setup>
import { type FormInstance, Message } from '@arco-design/web-vue'
import { useForm } from '@/hooks'
import { CouponApi, ParentApi } from '@/apis'
import { Regexp } from '@/utils'

interface Props {
  id?: string
}

const props = defineProps<Props>()

const emits = defineEmits(['change'])
const loading = ref(false)
const readonly = ref(true)
const dataId = ref('')
const dataDetail = ref<ParentApi.ParentDetailResp>()
const formRef = ref<FormInstance>()

const { form, resetForm } = useForm({
  name: undefined,
  mobilePhone: undefined,
  status: undefined,
})

// 查询详情
const getDataDetail = async () => {
  dataDetail.value = await ParentApi.getParentDetail(dataId.value)
  for (const key in form) {
    form[key] = dataDetail.value?.[key]
  }
  loading.value = false
}

const rules: FormInstance['rules'] = {
  name: [{ required: true, message: '请输入姓名' }],
  mobilePhone: [{ required: true, match: Regexp.Phone, message: '请输入正确的手机号码' }],
}

// 编辑
const onEdit = () => {
  readonly.value = false
}

// 取消
const onCancel = () => {
  readonly.value = true
  for (const key in form) {
    form[key] = dataDetail.value?.[key]
  }
  formRef.value?.clearValidate()
}

// 保存
const onSave = async () => {
  const invalidated = await formRef.value?.validate()
  if (invalidated) {
    return false
  }
  await ParentApi.updateParent(form, dataId.value)
  Message.success('修改成功')
  emits('change')
  readonly.value = true
}

// 优惠券
const isExpand = ref<boolean>(false)
const couponList = ref<CouponApi.CouponDetail[]>([])
const getCouponList = async () => {
  const query = {
    parentId: dataId.value,
    couponStatus: 1,
  }
  couponList.value = await CouponApi.getParentCouponList(query)
}

// 推荐人
const recommenderVisible = ref<boolean>(false)
const recommenderRef = ref<FormInstance>()
const recommenderForm = reactive({
  recommenderPhone: '',
})

const recommenderRules: FormInstance['rules'] = {
  recommenderPhone: [{ required: true, match: Regexp.Phone, message: '请输入正确的手机号码' }],
}

const onRecommenderCancel = () => {
  recommenderVisible.value = false
}

const onRecommenderUpdate = async () => {
  const invalidated = await recommenderRef.value?.validate()
  if (invalidated) {
    return false
  }
  try {
    const req = {
      parentId: dataId.value,
      recommenderPhone: recommenderForm.recommenderPhone,
    }
    await ParentApi.updateRecommender(req)
    Message.success('设置成功')
    return true
  // eslint-disable-next-line unused-imports/no-unused-vars
  } catch (_) {
    return false
  }
}

const openRecommenderModal = () => {
  recommenderForm.recommenderPhone = ''
  recommenderRef.value?.resetFields()
  recommenderVisible.value = true
}

watch(() => props.id, () => {
  if (props.id) {
    dataId.value = props.id
    getDataDetail()
    getCouponList()
  }
})
</script>

<template>
  <div class="parent-info">
    <div class="mr flex-row-between-center">
      <h3>家长信息</h3>
      <ReadonlyEditButton
        size="mini"
        :readonly="readonly"
        :deleteable="false"
        @edit="onEdit"
        @cancel="onCancel"
        @save="onSave"
      />
    </div>

    <div class="flex-col-start-center">
      <h2>
        {{ dataDetail?.name }}
      </h2>
      <a-space>
        <a-avatar :size="24" :style="{ backgroundColor: '#55b96d' }">
          <icon-wechat />
        </a-avatar>
        <a-avatar :size="24" :style="{ backgroundColor: '#3370ff' }">
          <icon-twitter-circle-fill />
        </a-avatar>
        <a-avatar :size="24">
          A
        </a-avatar>
        <a-avatar :size="24">
          B
        </a-avatar>
      </a-space>
    </div>
    <a-divider />
    <div class="detail">
      <a-form :model="form" :rules="rules" :readonly style="padding: 0 15px;" label-align="left" auto-label-width>
        <readonly-form-item label="姓名" :span="24" field="name">
          <a-input v-model.trim="form.name" placeholder="请输入姓名" :max-length="32" />
        </readonly-form-item>
        <readonly-form-item label="电话" :span="24" field="mobilePhone">
          <a-input v-model.trim="form.mobilePhone" placeholder="请输入电话" :max-length="11" />
        </readonly-form-item>
        <readonly-form-item label="用户名" :span="24" field="username" :editable="false">
          <span>{{ dataDetail?.username }}</span>
          <!-- <a-input v-model.trim="form.username" placeholder="请输入用户名" :max-length="11" disabled /> -->
        </readonly-form-item>
        <readonly-form-item label="推荐人" :span="24" field="recommender" :editable="false">
          <span v-if="dataDetail?.recommender">{{ dataDetail?.recommender }}</span>
          <a-link v-else size="mini" @click="openRecommenderModal">
            设置
          </a-link>
        </readonly-form-item>
        <readonly-form-item label="加入时间" :span="24" field="createTime" :editable="false">
          <span>{{ dataDetail?.createTime }}</span>
        </readonly-form-item>
        <readonly-form-item label="上次登录" :span="24" field="lastLoginTime" :editable="false">
          <span>{{ dataDetail?.lastLoginTime || '--' }}</span>
        </readonly-form-item>
        <readonly-form-item label="账号状态" :span="24" field="status" :editable="false">
          <CellStatus :status="dataDetail?.status || 0" on-text="正常" />
        </readonly-form-item>
        <readonly-form-item label="可用优惠券" :span="24" :editable="false">
          <a-space>
            <span class="count">{{ couponList.length }}张</span>
            <a-link size="mini" @click="isExpand = !isExpand">
              {{ isExpand ? '隐藏' : '查看' }}
            </a-link>
          </a-space>
        </readonly-form-item>
      </a-form>
      <div v-if="isExpand" class="coupons">
        <div v-for="(item, index) in couponList" :key="index" class="item">
          <a-image :width="36" :height="36" :src="item.template.image" :preview="false" />
          <div class="desc">
            <div class="name">
              {{ item.template.name }}
            </div>
            <div>有效天数：{{ item.template.validDays }}</div>
          </div>
        </div>
      </div>
    </div>
  </div>
  <a-modal v-model:visible="recommenderVisible" title="设置推荐人" width="300px" :on-before-ok="onRecommenderUpdate" @cancel="onRecommenderCancel">
    <a-form ref="recommenderRef" layout="vertical" :rules="recommenderRules" :model="recommenderForm">
      <a-form-item label="推荐人手机号" field="recommenderPhone">
        <a-input v-model.trim="recommenderForm.recommenderPhone" placeholder="请输入推荐人手机号" />
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style lang="less" scoped>
.parent-info {
  h2,
  h3 {
    color: #111;
    padding: 0 15px;
  }

  .detail {
    :deep(.arco-input-wrapper) {
      background-color: #fff;
    }
  }

  .coupons {
    max-height: 500px;
    overflow-y: auto;
    padding: 0 15px;
    padding-bottom: 15px;

    .item {
      border-radius: 4px;
      padding: 8px 10px;
      background: #fff;
      display: flex;
      align-items: center;

      &:not(:first-child) {
        margin-top: 8px;
      }

      .desc {
        font-size: 13px;
        margin-left: 10px;
        line-height: 18px;
        color: #888;

        .name {
          color: #111;
        }
      }
    }
  }

  .label {
    flex-shrink: 0;
    width: 90px;
    text-align: left;
    color: #999;
  }

  :deep(.arco-form-item) {
    margin-bottom: 0px;
  }

  :deep(.arco-card-header),
  :deep(.arco-card-body) {
    padding: 0;
  }

  .status {
    font-size: 14px;
    padding-left: 10px;
    position: relative;

    &::before {
      position: absolute;
      content: '';
      width: 6px;
      height: 6px;

      border-radius: 50%;
      left: 0;
      top: 50%;
      transform: translateY(-50%);
    }
  }

  .status0 {
    color: #00b42a;

    &::before {
      background: #00b42a;
    }
  }

  .status1 {
    color: #999;

    &::before {
      background: #999;
    }
  }

  .count {
    color: #165dff;
    font-size: 14px;
    margin-right: 24px;
  }
}
</style>
